<?php

/**
 * 这是一个消费者类，用于处理 WxoaTemplateMessageQueue 队列中的任务
 */

namespace app\wxoa\job;

// use JsonException;
use api\common\controller\BaseController;
use app\common\model\ContestModel;
use app\wxoa\model\DcpServerModel;
use app\wxoa\model\DcpUserModel;
use app\wxoa\model\template\TemplateFactory;
use app\wxoa\service\SchoolMessageService;
use think\queue\Job;
use app\wxoa\service\TemplateMessageService;
use app\dcp\manager\VoteManager;
use think\Db;

class NewContestStartMessage
{
    public static $templateName = 'newContestStartTemplate';
    public static $publishStatusConfig = [1, 2];// 1：全平台发布 2：小范围发布

    /**
     * fire方法是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data): void
    {
        if (empty($data) || !$data['contesId']) $job->delete();
        $contest = $this->selectContestById($data['contesId']);
        if (empty($contest))  $job->delete();
        $publishStatus = (int)$contest['publishStatus'];
        if (!in_array($publishStatus, self::$publishStatusConfig)) $job->delete();
        $weChatTemplate = $this->getWeChatTemplate($contest);
        $appTemplate = $this->getAppTemplate($contest);
        if ($publishStatus === 1) $isJobDone = $this->smallPublish($weChatTemplate, $appTemplate);
        if ($publishStatus === 2) $isJobDone = $this->allPublish($weChatTemplate, $appTemplate);
        if ($isJobDone) {
            $job->delete();
        } else if ($job->attempts() > 3) { //执行过3次的任务就删除掉
            $job->delete();
        }
    }
    private function smallPublish($status, $weChatMessage, $appMessage):bool
    {
        $smallAreaCode = BaseController::SMALL_AREA_INST_CODE; // 获取小范围发布的赛事机构code
        $userNameList = array_map(function ($val) {
            return 'admin' . $val;
        }, $smallAreaCode);
        // todo 暂时使用字符串连接方式操作其他数据库，项目完成前需要改成接口调用获取数据。
        $ossDatabase = Db::connect('mysql://dcp_db:dcpd1vxd1vx@47.97.16.45:3306/oss#utf8');
        // 直接获取了 username 集合，然后换取 OPENID
        foreach ($userNameList as $userNameListValue) {
            $userData[] = $ossDatabase->table('sp_wechat_relation')->where(['username' => $userNameListValue])->value('wechat_id');
            foreach ($userData as &$userDataValue) {
                // 1.发送微信通知
                SchoolMessageService::sendMessage($userDataValue, $weChatMessage['name'], $weChatMessage['data']);
                $userDataValue
                // 2.
            }
        }

        // 这时候 $userData 就可以发送微信通知了
        // 想要发送 app 通知 缺少 instaid 以及 domain 参数
        // 获取这两个参数需要表连接查询
        $domain = [];
        $instId = [];
        $userData = array_filter($userData, function ($value) {
            return !is_null($value);
        });
        foreach ($userData as $value) {
            SchoolMessageService::sendMessage($value, $weChatMessage['name'], $weChatMessage['data']);
            VoteManager::sendAppNotice($domain, $instId, $value, $appMessage);
        }
        return true;
    }
    private function allPublish($weChatMessage, $appMessage):bool
    {
        // todo 暂时使用字符串连接方式操作其他数据库，项目完成前需要改成接口调用获取数据。
        $ossDatabase = Db::connect('mysql://dcp_db:dcpd1vxd1vx@47.97.16.45:3306/oss#utf8');
        $divxDatabase = Db::connect('mysql://dcp_db:dcpd1vxd1vx@47.97.16.45:3306/divx_center#utf8');
        $nowTimeStr  = date('Y-m-d', strtotime(nowTimeStr()));
        $conditions = [];
        $conditions[] = ['enabled' => 1];
        $conditions[] = ['role_id', '<>',6];
        $divxUser = $divxDatabase->table('dcp_user')->alias('u')
            ->join('dcp_server s', 'u.server_id = s.id', 'left')
            ->where($conditions)
            ->field('u.username userName, u.inst_id instId, u.end_date endDate, s.domain')
            ->select()
            ->tooArray();
        foreach ($divxUser as $divxUserKey => &$divxUserValue) {
            if ($divxUserValue['endDate'] && (strtotime($divxUserValue['endDate']) < $nowTimeStr)) continue;
            $userData[] = $ossDatabase->table('sp_wechat_relation')->where(['username' => $divxUserValue['userName']])->field('wechat_id openId')->select()->toArray();
            foreach ($userData as $userDataKey => &$userDataValue) {
                SchoolMessageService::sendMessage($userDataValue['openId'], $weChatMessage['name'], $weChatMessage['data']);
                VoteManager::sendAppNotice($divxUserValue['domain'], $divxUserValue['instId'], $userDataValue['openId'], $appMessage);
            }
        }
        return true;
    }

    private function selectContestById($id){
        $where = ['id' => $id, 'deleted' => 0];
        return ContestModel::where($where)->field('name contestName, start_time startTime,end_time endTime, publish_status publishStatus')->find();

    }
    private function getTemplate($contestData){
        $templateName = self::$templateName;
        $templateData = [
            'first' => '活动报名成功通知，有新的活动正在火热进行中',
            'keyword1' => '活动名称：' . $contestData['contestName'],
            'keyword2' => '活动时间安排：' . $contestData['startTime'] . ' - ' . $contestData['endTime'],
            'keyword3' => '活动地点：前往【优学堂校长通公众号-赛事中心】即可参与',
            'remark' => '点击详情即可查看活动详情介绍'
        ];

        return ['name' => $templateName, 'data' => $templateData];
    }
    private function getAppTemplate($contestData){
        return  $contestData['contestName'] . '正在火热进行中，前往学校-活动中心查看精彩内容 立即前往 >';
    }
    /**
     * 业务处理
     * @param $data
     * @return bool
     */
    private function doTemplateMessageJob($data): bool
    {
        $nowTimeStr = date('Y-m-d', strtotime(nowTimeStr()));
        // weChat 通知消息
        // APP 通知消息
        if (in_array($publishStatus, self::$publishStatusConfig)) {

            if ($publishStatus === 1) { // 小范围发布
                $smallAreaCode = BaseController::SMALL_AREA_INST_CODE; // 范围发布的赛事的机构code
                $userNameData = array_map(function ($val) {
                    return 'admin' . $val;
                }, $smallAreaCode);

                // todo 暂时使用字符串连接方式操作其他数据库，项目完成前需要改成接口调用获取数据。
                $ossDatabase = Db::connect('mysql://dcp_db:dcpd1vxd1vx@47.97.16.45:3306/oss#utf8');

                foreach ($userNameData as $value) {
                    $userData[] = $ossDatabase->table('sp_wechat_relation')->where(['username' => $value])->value('wechat_id');
                }
                $userData = array_filter($userData, function ($value) {
                    return !is_null($value);
                });
            }

            if ($publishStatus === 2) {
                // todo 筛选条件：enabled 是否可用；role_id 非 6 所有的用户；end_time null && 非 null 数据大于当前时间
                // todo 获取用户 username 集合
                $userData = [];
            }
            // todo username 换取 openid 发送微信模板消息、
            // todo 调用 java divx_center 数据库中的 dcp_user 表，发送 app 通知
            for ($i = 0; $i <= count($userData); $i++ ) {
                TemplateMessageService::sendMessage($userData, $templateName, $templateData);
                VoteManager::sendAppNotice($data['domain'], $data['instId'], $userData, $content);
            }
        }
        return true;
    }
}
